package com.spring.cloud.eurekaclientgateway.route;

import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

//对路由的动态 添加删除
public class DynamicRoute {

    //动态新增路由
    public static void saveRoutes(){
        //创建restTemplate
        RestTemplate restTemplate = new RestTemplate();
        //获取路由定义
        RouteDefinition routeDefinition = routeDefinition();
        //包装请求体
        HttpEntity<RouteDefinition> request = new HttpEntity<>(routeDefinition);
        //请求路径
        String url = "http://localhost:3001/actuator/gateway/routes/hystrix";
        //http://localhost:3001/actuator/gateway/routes/hystrix POST更新添加 GET获取 DELETE 删除
        //Post请求
        ResponseEntity<Void> obj = restTemplate.postForEntity(url,request,Void.class);

    }

    //动态删除路由
    public static void deleteRoutes(){
        //创建restTemplate
        RestTemplate restTemplate = new RestTemplate();
        //请求路径
        String url = "http://localhost:3001/actuator/gateway/routes/hystrix";
        restTemplate.delete(url);
    }

    //创建路由定义  断言定义 过滤器定义
    private static RouteDefinition routeDefinition(){
        //路由定义
        RouteDefinition routeDefinition = new RouteDefinition();
        //设置路由编号
        routeDefinition.setId("hystrix");
        //设置URI
        routeDefinition.setUri(URI.create("lb://eureka-client-user"));
        //设置排序
        routeDefinition.setOrder(1000);
        //定义断言
        PredicateDefinition predicateDefinition = new PredicateDefinition("Path=/hystrix/**");
        List<PredicateDefinition> predicates = new ArrayList<>();
        //添加到列表中
        predicates.add(predicateDefinition);
        //将断言列表添加到路由定义中
        routeDefinition.setPredicates(predicates);

        //定义过滤器
        FilterDefinition filterDefinition = new FilterDefinition("AddRequestHeader=id,1");
        List<FilterDefinition> filters = new ArrayList<>();
        //将过滤器添加到列表中
        filters.add(filterDefinition);
        //将过滤器列表添加到路由定义中
        routeDefinition.setFilters(filters);

        //返回路由定义
        return routeDefinition;
    }
}
